#include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

const int SIZE = 1024;

struct sockaddr_in server;
int sock;

uint16_t serverport = 0;
std::string serverip;

static void usage(std::string proc)
{
    std::cout << "\nUsage:" << proc << " serverIp serverPort\n" << std::endl;
}

void process()
{
    char rece_buf[SIZE];
    std::string message;
    std::cout << "Please input message: ";
    std::getline(std::cin, message);
    for ( ; ; ) {
        sendto(sock, message.c_str(), message.size() , 0, (struct sockaddr*)&server, sizeof server);
        struct sockaddr_in temp;
        socklen_t len = sizeof temp;
        memset(rece_buf, 0, sizeof rece_buf);
        auto s = recvfrom(sock, rece_buf, sizeof rece_buf, 0, (struct sockaddr*)&temp, &len);
        if (s > 0) {
            printf("convert result: %s\n", rece_buf);
        }
        std::cout << "Please input message: ";
        std::getline(std::cin, message);
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3) {
        usage(argv[0]);
        exit(1);
    }

    sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) {
        std::cerr << "socket error." << std::endl;
        exit(2);
    }

    serverport = atoi(argv[2]);
    serverip = argv[1];
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[2]));
    server.sin_addr.s_addr = inet_addr(argv[1]);

    process();
    return 0;
}

